<?php

$max_shift = MAX_SHIFT_LEN;

$sql  = "select * , day(from_unixtime(`start`)) as day, ";
$sql .= "month(from_unixtime(`start`)) as month, ";
$sql .= "year(from_unixtime(`start`)) as year,  ";
$sql .= "(stop - start)/3600 as hours, ";
$sql .= "from_unixtime(`start`) as `Start Time`, ";
$sql .= "from_unixtime(`stop`) as `Stop Time` ";
$sql .= "from need ";
$sql .= "where processed = 0 ";
$sql .= "and (stop - start)/3600 >= $max_shift ";
$sql .= "order by (stop - start)/3600 desc ";


$results = lomgetit($sql);
simple_table($results);

foreach ($results as $r){
	$start = $r['start'];
	$stop = $r['stop'];

	print "Need auto: {$r['auto']}\n";

	//breakdown into two pieces
	$first_avail = get_avail_start($start);
	if (count($first_avail) == 0){print "<h1>ERROR: Not Enough Avail!</h1>"; $multi_break = 1; break;}
	print "<h1>First Half Availability</h1>";


	$last_avail = get_avail_stop($stop);
        if (count($last_avail) == 0){print "<h1>ERROR: Not Enough Avail!</h1>"; $multi_break = 1; break;}

	if ($multi_break == 1){include "assign.multibreak.php"; continue;}


        print "<h1>Last Half Availability</h1>";
	foreach ($first_avail as $f){
	        foreach ($last_avail as $l){
			if ($l['employee'] == $f['employee']){continue;}
			print "First: {$f['employee']} min,max = {$f['min']},{$f['max']}\n";
			print "Last: {$l['employee']} min,max = {$l['min']},{$l['max']}\n";
			if (($f['min'] == $l['min']) and ($f['max'] == $l['max'])){
				if ($r['hours'] % 2 == 0){
        			        $shift_len[0] = $r['hours']/2;
			                $shift_len[1] = $r['hours']/2;
			        }else{
			                $shift_len[0] = floor($r['hours']/2);
			                $shift_len[1] = ceil($r['hours']/2);
        			}//else . . . if ($qty_shifts % 2 == 0)
			}//if (($f['min'] == $l['min']) and ($f['max'] == $l['max']))
			else{}//change shift length here
			//First Shift
			$first_start = $r['start'];
			$first_stop =  $first_start + $shift_len[0]*3600;
			print "First: {$first_start} to {$first_stop}\n";
			//Last Shift
			$last_start = $first_stop;
			$last_stop = $r['stop'];

if (($first_start == $last_start) or ($first_stop == $last_stop)){print "<h1>yikes!!!!!</h1>"; die();}


			$verify_first = verify_scheduling_protocols($first_start, $first_stop, $f['employee']);
			if ($verify_first == 1){
			$verify_last = verify_scheduling_protocols($last_start, $last_stop, $l['employee']);}
			if (verify_last== 1){continue;}

			//sked_shift($start, $stop, $employee, $avail = null, $need = null)
			$sked_first = sked_shift($first_start, $first_stop, $f['employee'], $f['auto']);
			if ($sked_first ==1){
				$sked_last = sked_shift($last_start, $last_stop, $l['employee'], $l['auto'], $r['auto']);}
			if ($sked_last == 1){break 2;}


		}//foreach ($last_avail as $l)
	}//foreach ($first_avail as $f)



}

